package org.asg.dis.controller;

import io.jsonwebtoken.Claims;
import jakarta.persistence.EntityNotFoundException;
import jakarta.validation.Valid;
import org.asg.dis.model.*;
import org.asg.dis.request.CreateShipmentReq;
import org.asg.dis.request.UserCancelShipmentReq;
import org.asg.dis.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class UserController {

    private final ShipmentService shipmentService;
    private final ExpressStationService expressStationService;
    private final CourierService courierService;
    private final RoleService roleService;
//    private final MessageProducer messageProducer;
    private final UserService userService;
    private final TraceService traceService;
    private final ComplaintService complaintService;
    @Autowired
    public UserController(
            ShipmentService ss,
            ExpressStationService es,
            CourierService courierService, RoleService roleService, UserService userService,
//            MessageProducer messageProducer,
            TraceService traceService,
            ComplaintService complaintService
    ) {
        this.shipmentService = ss;
        this.expressStationService = es;
        this.courierService = courierService;
        this.roleService = roleService;
        this.userService = userService;
//        this.messageProducer = messageProducer;
        this.traceService = traceService;
        this.complaintService = complaintService;
    }

    @GetMapping("/info")
    @PreAuthorize("hasRole('User')")
    public ApiResponse<?> info() {
        System.out.println("进入info: 验证成功!");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println(authentication);

        Claims c = (Claims) authentication.getPrincipal();
        Long userId = c.get("userId", Long.class);
        System.out.println("User ID: " + userId);

        Optional<User> userOpt = userService.getUserById(userId);
        System.out.println("User: " + userOpt);

        if (userOpt.isPresent()) {
            User user = userOpt.get();
//
//            // 构建用户信息
//            Map<String, Object> userInfo = new HashMap<>();
//            userInfo.put("userId", user.getUserId());
//            userInfo.put("userName", user.getUsername());
//            userInfo.put("avatar", null); // 如有头像 URL，可替换 null
//            System.out.println("userInfo: " + userInfo);
//
//            // 构建响应数据
//            Map<String, Object> response = new HashMap<>();
//            response.put("user", userInfo);
//            response.put("roles", roleNames);
//            response.put("permissions", permissions);
//
//            System.out.println("返回响应: info!");
//            System.out.println("Final response: " + response);
            System.out.println("return info");
            return ApiResponse.ok(user);
        } else {
            return ApiResponse.error(HttpStatus.NOT_FOUND.value(), "用户不存在");
        }
    }

    // 将 role_id 映射到 role_name
    private String mapRoleIdToRoleName(int roleId) {
        switch (roleId) {
            case 1: return "User";
            case 2: return "Courier";
            case 3: return "Staff"; // 拼写更正: "Stuff" -> "Staff"
            case 4: return "Admin";
            default: return "Unknown"; // 默认值，用于处理未知的角色 ID
        }
    }




    @PostMapping("/send")
    @PreAuthorize("hasRole('User')")
    public ApiResponse<UUID> createShipment(@RequestBody CreateShipmentReq request) {
        // 将请求映射到实体类
        Shipment shipment = new Shipment();
        shipment.setSenderId(request.senderId());
        shipment.setSenderName(request.senderName());
        shipment.setSenderPhoneNumber(request.senderPhoneNumber());
        shipment.setSenderRegion(request.senderRegion());
        shipment.setSenderDetailedAddress(request.senderDetailedAddress());
        shipment.setReceiverName(request.receiverName());
        shipment.setReceiverPhoneNumber(request.receiverPhoneNumber());
        shipment.setReceiverRegion(request.receiverRegion());
        shipment.setReceiverDetailedAddress(request.receiverDetailedAddress());
        shipment.setExpressService(ExpressService.valueOf(request.expressService()));
        shipment.setType(request.type());
        shipment.setWeight(request.weight());
        shipment.setAmount(request.amount());
        shipment.setNote(request.note());
        shipment.setExpectedTime(request.expectedTime());
        shipment.setPaymentMethod(PaymentMethod.valueOf(request.paymentMethod()));
        shipment.setStatus(ShipmentStatus.valueOf("已下单")); // 设置初始状态
        shipment.setLocation(request.location());
        shipment.setSenderId((long)1);
        // 保存货件信息
        Shipment s =  shipmentService.saveShipment(shipment);
//        expressStationService.assignShipment(request.location());
        //快件创建后,快递站会进行派件,派件完毕后应当<通知>负责收件的快递员和快递站,最后通知用户派件完成
        //TODO 返回处理
        return ApiResponse.ok(s.getShipmentId());
    }

    @PostMapping("/cancel")
    @PreAuthorize("hasRole('User')")
    public ApiResponse<String> cancelShipment(@RequestBody UserCancelShipmentReq request){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        shipmentService.updateShipment(UUID.fromString(request.shipmentId()), ShipmentStatus.退单);
        //TODO 取消快递员的任务 发送消息给快递员和营业厅
        Claims c = (Claims)authentication.getPrincipal();
        courierService.cancel(request.shipmentId());
        Message courierMessage = new Message(
                MessageType.DELIVERY,
                request.shipmentId(),
                "退单提醒",
                "",
                c.get("userId", Long.class),
                request.courierId(),
                MessageStatus.UNREAD,
                request.timestamp()
        );
//        messageProducer.sendMessage(courierMessage);

        Message stationMessage = new Message(
                MessageType.COMPLAINT,
                request.shipmentId(),
                "退单提醒",
                "",
                c.get("userId", Long.class),
                request.expressStationId(),
                MessageStatus.UNREAD,
                request.timestamp()
        );
        return ApiResponse.ok();
    }

    @PostMapping("/pickup")
    @PreAuthorize("hasRole('User')")
    public ApiResponse<String> fetchPackage(@RequestParam String shipmentId) {
        //TODO 取件完成后同样会通知快递站点和快递员
        shipmentService.updateShipment(UUID.fromString(shipmentId), ShipmentStatus.已签收);

        return ApiResponse.ok("Package fetched successfully!");
    }

    @PostMapping("/query")
    @PreAuthorize("hasRole('User')")
    public ApiResponse<String> queryShipmentLocation(@RequestBody String shipmentId) {
        // 从数据库中根据 UUID 获取 Shipment 实体对象
        Shipment shipment = shipmentService.getShipmentById(shipmentId)
                .orElseThrow(() -> new EntityNotFoundException("Shipment not found with ID: " + shipmentId));
        traceService.getTrackingInfo(shipment);//这里出现问题
        return ApiResponse.ok("Package location queried successfully!");
    }

    @PostMapping("/complain")
    @PreAuthorize("hasRole('User')")
    public ApiResponse<String> complain(@Valid @RequestBody Complaint request) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Claims c = (Claims) authentication.getPrincipal();
        if(request.getTargetId() != null){
            Message courierMessage = new Message(
                    MessageType.COMPLAINT,
                    request.getShipmentId(),
                    "客户投诉",
                    request.getSummary() + ' ' + request.getDetail(),
                    c.get("userId", Long.class),
                    request.getTargetId(),
                    MessageStatus.UNREAD,
                    request.getTimestamp()
            );
//            messageProducer.sendMessage(courierMessage);
        }

        Message stationMessage = new Message(
                MessageType.COMPLAINT,
                request.getShipmentId(),
                "客户投诉",
                request.getSummary() + ' ' + request.getDetail(),
                c.get("userId", Long.class),
                request.getTargetId(),
                MessageStatus.UNREAD,
                request.getTimestamp()
        );

//        messageProducer.sendMessage(stationMessage);
        //这里的request中的id显然是null,存入数据库时自增id会自动设置吗
        complaintService.createComplaint(request);
        return ApiResponse.ok("Complaint submitted successfully.");
    }

//    @PostMapping("/advise")
//    @PreAuthorize("hasRole('User')")
//    public ApiResponse<String> advise(){
//        expressStationService.handleAdvise();
//        return ApiResponse.ok();
//    }

    @PostMapping("/book")
    @PreAuthorize("hasRole('User')")
    public ApiResponse<String> book(){
        return ApiResponse.ok();
    }

    @PostMapping("/pay")
    @PreAuthorize("hasRole('User')")
    public ApiResponse<String> pay(){
        return ApiResponse.ok();
    }
}
